package cn.bnjy.util;

import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

/**
 * 描述：执行linux命令
 *
 * @since: 2018/11/26 22:55
 * @author: chavin
 */
@Slf4j
public class ShellCmdUtils {

    private ShellCmdUtils() {

    }

    /**
     * 执行linux命令
     * @param command
     * @return
     */
    public static String run(String command) {
        log.info("执行Linux脚本: {}", command);
        LocalDateTime startTime = LocalDateTime.now();
        Scanner input = null;
        String result = "";
        Process process = null;
        try {
            String[] cmd = new String[] {"sh", "-c", command};
            process = Runtime.getRuntime().exec(cmd);
            //等待命令执行完成
            process.waitFor(10, TimeUnit.SECONDS);
            InputStream is = process.getInputStream();
            input = new Scanner(is);
            while (input.hasNextLine()) {
                result += input.nextLine() + "\n";
            }
        } catch (Exception e) {
            log.error("执行Linux命令失败：", e);
        } finally {
            if (input != null) {
                input.close();
            }
            if (process != null) {
                process.destroy();
            }
        }
        LocalDateTime endTime = LocalDateTime.now();
        long time = ChronoUnit.MILLIS.between(startTime, endTime);
        log.info("执行Linux脚本完毕，耗时：{}ms，返回：{}", time, result);
        return result;
    }

}
